package walletuserslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/uniqueid"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserOrderLogic {
	return &UserOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户order
func (l *UserOrderLogic) UserOrder(in *pb.UserOrderReq) (*pb.UserOrderResp, error) {
	defer utils.RecoverPanic()

	var err error
	// 查询钱包
	var uw *wallet.UserWallet
	uw, err = l.svcCtx.UserWalletModel.FindOneByUidMoneyType(l.ctx, in.Uid, in.MoneyType)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		if err == wallet.ErrNotFound {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletNotFound, "wallet not found")
		}
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var dOrderMoneyAmount decimal.Decimal
	dOrderMoneyAmount, err = decimal.NewFromString(in.MoneyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	dOrderMoneyAmount = dOrderMoneyAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale))
	var dUwBalance decimal.Decimal
	dUwBalance = decimal.NewFromInt(uw.Amount)

	// 判断余额是否足够
	if dUwBalance.LessThan(dOrderMoneyAmount) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletBalanceNotEnoughForOrder, "balance not enough")
	}

	// 创建order流水
	var orderFlow wallet.UserGameOrderFlow
	iOrderMoneyAmount := dOrderMoneyAmount.IntPart()
	orderFlow = wallet.UserGameOrderFlow{
		FlowNo:         uniqueid.GenFlowNoX(),
		ExternalFlowNo: in.ExternalFlowNo,
		MoneyType:      in.MoneyType,
		Uid:            in.Uid,
		MoneyAmount:    iOrderMoneyAmount,
		GameId:         in.GameId,
		ProviderId:     in.ProviderId,
		State:          walletkey.OrderFlowStateInit,
	}

	loc, _ := time.LoadLocation(dbkey.DateTimeZone)
	orderFlow.OrderTime, err = time.ParseInLocation(dbkey.DateTimeCNFormat, in.OrderTime, loc)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	err = l.svcCtx.UserWalletModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		// 更新钱包余额
		err2 := l.svcCtx.UserWalletModel.DecrAmountTrans(ctx, tx, iOrderMoneyAmount, uw.Id, in.Uid, in.MoneyType)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		// 创建order流水
		_, err2 = l.svcCtx.UserGameOrderFlowModel.InsertTrans(ctx, tx, &orderFlow)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	var rsp pb.UserOrderResp
	rsp.FlowNo = orderFlow.FlowNo
	rsp.Balance = dUwBalance.Sub(dOrderMoneyAmount).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)
	return &rsp, nil
}
